package org.shreker.shan.website.business.controller;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.shreker.shan.core.domain.Log;
import org.shreker.shan.core.domain.Login;
import org.shreker.shan.core.service.ILogService;
import org.shreker.shan.core.service.ILoginService;
import org.shreker.shan.core.util.LoginContext;
import org.shreker.shan.core.util.ResultJSON;
import org.shreker.shan.website.base.controller.WebSiteController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController extends WebSiteController {

	@Autowired
	private ILoginService loginService;

	@Autowired
	private ILogService logService;

	@RequestMapping("/register")
	@ResponseBody
	public ResultJSON register(String username, String password) {
		ResultJSON json = new ResultJSON();
		try {
			loginService.register(username, password, Login.IDENTITY_USER);
			json.setSuccess(true);
			json.setInfo("注册成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.setSuccess(false);
			json.setInfo(e.getMessage());
		}
		return json;
	}

	@RequestMapping("/login")
	@ResponseBody
	public ResultJSON login(String username, String password, HttpServletRequest request) throws Exception {
		ResultJSON json = new ResultJSON();
		Log log = new Log();
		log.setLoginIp(request.getRemoteAddr());
		log.setLoginTime(new Date());
		log.setUsername(username);
		try {
			loginService.login(username, password, Login.IDENTITY_USER);
			json.setSuccess(true);
			json.setInfo("登录成功!");

			log.setUserId(LoginContext.getCurrentLogin().getId());
			log.setResult(Log.LOG_SUCCESS);
			logService.save(log);
		} catch (Exception e) {
			json.setSuccess(false);
			json.setInfo(e.getMessage());

			log.setResult(Log.LOG_FAIL);
			logService.save(log);
		}
		return json;
	}

	@RequestMapping("/logout")
	@ResponseBody
	public ResultJSON logout() throws Exception {
		ResultJSON json = new ResultJSON();
		try {
			LoginContext.removeCurrentLogin();
			json.setSuccess(true);
			json.setInfo("注销成功!");
		} catch (Exception e) {
			json.setSuccess(false);
			json.setInfo("注销失败");
		}
		return json;
	}
}
